<template>
  <div class="category-page page">
    <DraggableSider
      :minWidth="250"
      :side="'left'"
      :defaultToggled="true"
      :autoHide="true"
      :needSiderToggle="false"
    >
      <template #content>
        <div class="tree-wrapper">
          <div class="tool-wrapper flex items-center">
            <a-input
              v-model:value="searchText"
              placeholder="搜索类目树"
              size="small"
              allow-clear
            >
              <template #suffix>
                <SearchOutlined />
              </template>
            </a-input>
            <a-dropdown trigger="click">
              <FilterOutlined
                pl-5px
                cursor-pointer
                hover:text-primary
                :class="{
                  'text-primary': filterPublishActive,
                }"
              />
              <template #overlay>
                <a-menu :selected-keys="[filterPublish]">
                  <a-menu-item
                    v-for="item in publishFilters"
                    :key="item.key"
                    @click="changeFilterPublish(item.key)"
                  >
                    {{ item.title }}
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>

          <div
            flex
            items-center
            px-2
            text-14px
            h-24px
            border-b="1px solid #d9d9d9"
          >
            <div text-primary cursor-pointer @click="expandAll">全部展开</div>
            <div text-primary cursor-pointer ml-2 @click="collapseAll">
              全部收起
            </div>
            <div class="flex-1"></div>
            <div
              class="i-mdi-my-location hover-text-primary cursor-pointer"
              @click="goNode"
            ></div>
          </div>
          <div flex-1 ref="treeWrapperRef">
            <a-spin :spinning="treeLoading">
              <a-empty v-if="filteredTreeData.length === 0" />
              <a-directory-tree
                ref="treeRef"
                v-else
                v-model:expandedKeys="currentExpandedKeys"
                :selectedKeys="currentSelectedKeys"
                :field-names="fieldNames"
                :tree-data="filteredTreeData"
                @select="onTreeNodeSelect"
                @expand="onTreeNodeExpand"
                :height="height"
                :key="height"
              >
                <template #icon="{ dataRef }">
                  <FolderOutlined v-if="dataRef.type === 'TRUNK'" />
                  <ProfileOutlined v-if="dataRef.type === 'LEAF'" />
                </template>
                <template #title="{ dataRef }">
                  <span
                    class="node truncate"
                    :class="{
                      selected: currentSelectedKeys.includes(dataRef.id),
                      'cursor-grab': currentUser?.isCategorySystemAdmin,
                    }"
                    :title="dataRef.categoryName"
                  >
                    {{ dataRef.categoryName }}
                    <a-dropdown>
                      <MoreOutlined class="icon-menu" />
                      <template #overlay>
                        <a-menu
                          @click="
                            e => {
                              handleMenuClick(e, dataRef);
                            }
                          "
                        >
                          <template v-if="dataRef.type === 'TRUNK'">
                            <a-menu-item key="newClass">新建分类</a-menu-item>
                            <a-menu-item key="newCategory">
                              新建类目
                            </a-menu-item>
                          </template>
                          <!-- <a-menu-item v-if="dataRef.type === 'LEAF'" key="merge"
                          >类目对齐</a-menu-item
                        >
                        <a-menu-item v-if="dataRef.type === 'LEAF'" key="sync"
                          >同步数据</a-menu-item
                        > -->
                          <!-- <a-menu-item
                          v-if="!!dataRef.parentId"
                          :disabled="dataRef.serialNum === 1"
                          key="moveup"
                          >上移</a-menu-item
                        >
                        <a-menu-item
                          v-if="!!dataRef.parentId"
                          :disabled="dataRef.serialNum === dataRef.serialCount"
                          key="movedown"
                          >下移</a-menu-item
                        > -->
                          <a-menu-item v-if="!!dataRef.parentId" key="edit">
                            编辑
                          </a-menu-item>
                          <a-menu-item v-if="!!dataRef.parentId" key="delete">
                            删除
                          </a-menu-item>
                          <template v-if="dataRef.type === 'LEAF'">
                            <a-menu-item
                              v-if="dataRef.publishStatus"
                              key="unPublish"
                            >
                              取消发布
                            </a-menu-item>
                            <a-menu-item
                              v-if="!dataRef.publishStatus"
                              key="publish"
                            >
                              发布
                            </a-menu-item>
                          </template>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </span>
                </template>
              </a-directory-tree>
            </a-spin>
          </div>
        </div>
      </template>
    </DraggableSider>
    <div v-if="currentSelectedKeys.length > 0" class="info-wrapper">
      <a-divider orientation="left">基本信息</a-divider>
      <div class="basic-info-wrapper">
        <img :src="currentSelectedCategory.categoryImgUrl || unknownImg" />
        <a-descriptions :title="currentSelectedCategory.categoryName">
          <a-descriptions-item label="分类">
            {{ currentSelectedCategory.categoryPath }}
          </a-descriptions-item>
          <a-descriptions-item label="创建人">
            {{ currentSelectedCategory.creator?.name }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ currentSelectedCategory.createTime }}
          </a-descriptions-item>

          <a-descriptions-item
            label="最近对齐时间"
            v-if="currentSelectedCategory.alignMode != 'CUSTOM'"
          >
            {{ currentSelectedCategory.alignTime }}
          </a-descriptions-item>

          <a-descriptions-item
            label="最近同步时间"
            v-if="currentSelectedCategory.alignMode != 'CUSTOM'"
          >
            {{ currentSelectedCategory.syncTime }}
          </a-descriptions-item>
          <a-descriptions-item
            label="描述"
            :contentStyle="{
              display: '-webkit-box',
              '-webkit-line-clamp': 3,
              '-webkit-box-orient': 'vertical',
              overflow: 'hidden',
              'text-overflow': 'ellipsis',
            }"
          >
            <span :title="currentSelectedCategory.categoryDesc">
              {{ currentSelectedCategory.categoryDesc }}
            </span>
          </a-descriptions-item>
          <a-descriptions-item
            label="来源网站"
            v-if="currentSelectedCategory.alignMode != 'CUSTOM'"
          >
            <div flex flex-wrap>
              <span
                text-primary
                mr-10px
                cursor-pointer
                v-for="item in websites[currentSelectedCategory.id] ?? []"
                :key="item.id"
                @click="toSource(item.websiteUrl)"
              >
                {{ item.websiteName }}
              </span>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="发布状态">
            {{ currentSelectedCategory.publishStatus ? '已发布' : '未发布' }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
      <template v-if="currentSelectedCategory.type == 'TRUNK'">
        <a-divider orientation="left">子分类、子类目</a-divider>
        <a-empty v-if="!currentSelectedCategory.children.length"></a-empty>
        <div class="category-list">
          <div
            v-for="item in currentSelectedCategory.children"
            :key="item.id"
            class="category-list-item"
            @click="handleClickCategoryItem(item)"
          >
            <img
              :src="
                item.categoryImgUrl ||
                (item.type == 'TRUNK' ? folder : unknownImg)
              "
            />
            <div class="content">
              <span>{{ item.categoryName }}</span>
            </div>
          </div>
        </div>
      </template>
      <template v-else>
        <a-divider orientation="left">条件与选项</a-divider>
        <div class="table-wrapper">
          <a-space mb-4>
            <a-button
              type="primary"
              danger
              v-if="currentSelectedCategory.publishStatus"
              @click="unPublish(currentSelectedCategory.categoryCode)"
            >
              取消发布
            </a-button>
            <a-button
              type="primary"
              v-else
              @click="publish(currentSelectedCategory.categoryCode)"
              :loading="publishLoading"
            >
              发布
            </a-button>

            <a-button
              type="primary"
              @click="createCustom"
              v-if="currentSelectedCategory.alignMode == 'CUSTOM'"
            >
              自建类目
            </a-button>
            <a-button type="primary" @click="onMergeClick">类目对齐</a-button>
            <a-button
              v-if="currentSelectedCategory.alignMode != 'CUSTOM'"
              type="primary"
              @click="onSyncCategoryClick"
              :loading="syncLoading"
              :disabled="!syncable"
            >
              同步数据
            </a-button>
            <a-button type="primary" @click="onResetClick">重置</a-button>
          </a-space>
          <a-table
            :dataSource="dataSource"
            :columns="columns"
            :loading="tableLoading"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'options'">
                <a
                  v-if="!!record.options"
                  href="javascript:void(0)"
                  @click="onOptionsClick(record)"
                >
                  查看
                </a>
                <span v-else>-</span>
              </template>
            </template>
          </a-table>
        </div>
      </template>
    </div>
    <div class="no-category-wrapper" v-else>
      <img src="@/assets/engineer_dao.png" />
      <div>欢迎使用一刀云·类目管理系统</div>
      <div>请选择一个类目</div>
    </div>
  </div>
  <a-modal
    v-model:open="optionModalOpen"
    :title="optionModelTitle"
    :footer="null"
  >
    <a-table :dataSource="optionDataSource" :columns="optionColumns">
      <template #bodyCell="{ column, value, record }">
        <template v-if="column.dataIndex == 'optionValueImgUrl'">
          <a-popover>
            <template #content>
              <img
                :src="record.optionValueImgUrl"
                :style="{ maxHeight: '200px' }"
              />
            </template>
            <img
              v-if="!!record.optionValueImgUrl"
              class="option-image"
              :style="{ height: '32px' }"
              :src="record.optionValueImgUrl"
            />
          </a-popover>
        </template>
      </template>
    </a-table>
  </a-modal>
  <ClassifyModal
    ref="classifyModalRef"
    :parentTree="parentTree"
    @ok="onClassifyModalOk"
  />
</template>

<script setup>
import { onMounted, ref, createVNode, computed } from 'vue';

import { useRouter } from 'vue-router';
import { debounce } from 'lodash-es';
import { useUserStore } from '@/store/user';

import { useCategoryStore } from '@/store/category';
import { breadFirstTree, findTreeNode } from '@/utils/util';
import { FilterOutlined } from '@ant-design/icons-vue';
import {
  getCategoryTree,
  getCategoryDetail,
  deleteCategory,
  resetCategory,
  moveCategory,
  syncCategory,
} from '@/api/hc_category';
import unknownImg from '@/assets/unknown.png';
import folder from '@/assets/folder.svg';
import { useDrag } from './useDrag';

const router = useRouter();
const { setSelectCategory } = useCategoryStore();
const userStore = useUserStore();

const classifyModalRef = ref();

const searchText = ref('');

const treeLoading = ref(false);

const tableLoading = ref(false);

const optionModalOpen = ref(false);

const optionModelTitle = ref('');
const treeData = ref([]);
const currentSelectedKeys = ref([]);
const currentExpandedKeys = ref([]);

const currentSelectedCategory = computed(() => {
  const [id] = currentSelectedKeys.value;
  if (id) {
    return findNodeById(id, treeData.value) || {};
  }
  return {};
});
const { currentUser } = storeToRefs(userStore);
const treeLoaded = ref(false);

const syncable = computed(() => {
  if (!currentSelectedKeys.value.length) return false;

  const { alignTime, syncTime } = currentSelectedCategory.value;
  if (!syncTime) {
    return true;
  } else {
    const alignTimeDate = new Date(alignTime);
    const syncTimeDate = new Date(syncTime);
    return syncTimeDate < alignTimeDate;
  }
});

const canAction = computed(
  () =>
    currentUser.value.isCategorySystemAdmin ||
    currentUser.value.userId == currentSelectedCategory.value.creator?.userId,
);

const fieldNames = {
  key: 'id',
  title: 'name',
};

const columns = [
  {
    title: '条件编码',
    dataIndex: 'conditionCode',
    key: 'conditionCode',
  },
  {
    title: '条件名称',
    dataIndex: 'conditionName',
    key: 'conditionName',
  },
  {
    title: '条件选项',
    key: 'options',
    dataIndex: 'options',
  },
  // {
  //   title: '条件类型',
  //   key: 'conditionType',
  //   dataIndex: 'conditionType',
  //   sorter: (a, b) => a.conditionType.localeCompare(b.conditionType),
  // },
];

const optionColumns = [
  // {
  //   title: '选项代码',
  //   dataIndex: 'optionCommonCode',
  //   key: 'optionCommonCode',
  // },

  {
    title: '选项',
    dataIndex: 'optionName',
    key: 'optionName',
  },
  {
    title: '图片',
    dataIndex: 'optionValueImgUrl',
    key: 'optionValueImgUrl',
  },
  {
    title: '来源网站',
    key: 'optionValueSiteCodes',
    dataIndex: 'optionValueSiteCodes',
    sorter: (a, b) =>
      a.optionValueSiteCodes.localeCompare(b.optionValueSiteCodes),
  },
];

const dataSource = ref([]);
const optionDataSource = ref([]);

const parentTree = computed(() => {
  let copiedTree = JSON.parse(JSON.stringify(treeData.value));
  copiedTree = copiedTree.filter(ele => ele.type === 'TRUNK');
  breadFirstTree(
    copiedTree,
    node => {
      node.selectable = true;
      node.children = node.children.filter(ele => ele.type === 'TRUNK');
      return true;
    },
    'children',
  );
  return copiedTree;
});

const filteredTreeData = computed(() => {
  let copiedTree = cloneDeep(treeData.value);
  return findTreeNode(copiedTree, node => {
    // return node.categoryName.indexOf(searchText.value) > -1;
    const isInclude = node.categoryName.indexOf(searchText.value) > -1;
    const isPublish = !!node.publishStatus;
    if (filterPublish.value == 'published') {
      return isInclude && isPublish;
    } else if (filterPublish.value == 'unpublished') {
      return isInclude && !isPublish;
    } else {
      return isInclude;
    }
  });
});

const debounceSearch = debounce(() => {}, 500);

const onMergeClick = () => {
  if (currentSelectedKeys.value.length === 0) {
    message.info('请选择一个类目');
    return;
  }
  const [id] = currentSelectedKeys.value;
  if (!canAction.value) {
    message.error('您不是该类目的创建人，无法操作');
    return;
  }
  router.push({ path: `/selection` });
};

const onResetClick = () => {
  if (currentSelectedKeys.value.length === 0) {
    message.info('请选择一个类目');
    return;
  }
  const [id] = currentSelectedKeys.value;
  if (!canAction.value) {
    message.error('您不是该类目的创建人，无法操作');
    return;
  }
  Modal.confirm({
    title: '警告',
    icon: createVNode(ExclamationCircleOutlined),
    content: `重置类目将会删除其所有已配置的条件和选项，是否继续？`,
    okText: '是',
    okType: 'danger',
    cancelText: '否',
    onOk() {
      onResetCategoryConfirm(id);
    },
    onCancel() {},
  });
};

const toSource = url => {
  if (!url) return;
  window.open(url);
};
const handleMenuClick = (e, dataRef) => {
  if (
    ['moveup', 'movedown', 'edit', 'delete', 'publish', 'unPublish'].includes(
      e.key,
    )
  ) {
    if (
      !currentUser.value.isCategorySystemAdmin &&
      currentUser.value.userId !== dataRef.creator?.userId
    ) {
      const msgText = dataRef.type === 'LEAF' ? '类目' : '分类';
      message.error(`您不是该${msgText}的创建人，无法操作`);
      return;
    }
  }

  switch (e.key) {
    case 'newClass':
      classifyModalRef.value.onNew(dataRef.id, 'TRUNK');
      break;
    case 'newCategory':
      classifyModalRef.value.onNew(dataRef.id, 'LEAF');
      break;
    // case 'merge':
    //   setSelectCategory(dataRef);
    //   router.push({ path: 'selection' });
    //   break;
    // case 'sync':
    //   onSyncCategory(dataRef.categoryCode);
    //   break;
    case 'moveup':
      onMoveClick(dataRef, 'UP');
      break;
    case 'movedown':
      onMoveClick(dataRef, 'DOWN');
      break;
    case 'edit':
      classifyModalRef.value.onEdit(dataRef, dataRef.type);
      break;
    case 'delete':
      onDeleteCategoryClick(dataRef);
      break;
    case 'publish':
      publish(dataRef.categoryCode);
      break;
    case 'unPublish':
      unPublish(dataRef.categoryCode);
      break;
    default:
      return;
  }
};

const syncLoading = ref(false);
const onSyncCategoryClick = () => {
  const [id] = currentSelectedKeys.value;
  if (!canAction.value) {
    message.error('您不是该类目的创建人，无法操作');
    return;
  }
  syncLoading.value = true;
  syncCategory(currentSelectedCategory.value.categoryCode)
    .then(async res => {
      if (res.code === 'ok') {
        message.success('数据已同步');
        await getCategoryTreeCaller();
      } else {
        message.error(res.message ?? '同步数据时出现未知错误');
      }
    })
    .catch(err => {
      console.log(`output->err`, err);
      message.error(err?.message ?? '同步数据时出现未知错误');
    })
    .finally(() => {
      syncLoading.value = false;
    });
};

const onMoveClick = (category, direction) => {
  moveCategory(category.id, direction).then(res => {
    if (res.code === 'ok') {
      getCategoryTreeCaller();
    }
  });
};

const websites = ref({});

const onTreeNodeSelect = (selectedKeys, e) => {
  const [newId] = selectedKeys;
  const { id, categoryCode } = currentSelectedCategory.value;
  setSelectCategory(e.node.dataRef);
  if (id != newId) {
    currentSelectedKeys.value = [newId];
    fetchCategoryDetail();
  }
};

const fetchCategoryDetail = () => {
  tableLoading.value = true;
  getCategoryDetail(currentSelectedCategory.value.categoryCode)
    .then(res => {
      if (res.code === 'ok') {
        dataSource.value = res.data.filterConditions.map(ele => {
          const { conditionCommonNo, conditionName, options } = ele;
          const obj = {
            conditionCode: conditionCommonNo,
            conditionName,
            options,
            conditionType: '条件',
          };
          return obj;
        });
        websites.value[currentSelectedCategory.value.id] =
          res.data.websites || [];
      }
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

const onTreeNodeExpand = (expandedKeys, e) => {
  const { node } = e;
  if (node.type == 'TRUNK') {
    // 选中分类节点
    currentSelectedKeys.value = [e.node.id];
  }
  // currentExpandedKeys.value = expandedKeys;
};

const handleClickCategoryItem = node => {
  const { type, id, parentId } = node;
  const expandKeys = currentExpandedKeys.value;
  if (!expandKeys.includes(parentId)) {
    expandKeys.push(parentId);
  }
  expandKeys.push(id);
  if (type == 'TRUNK') {
    onTreeNodeExpand(expandKeys, { node });
  } else {
    onTreeNodeSelect([node.id], { node: { dataRef: node } });
  }
};

const onDeleteCategoryClick = category => {
  if (category.type === 'LEAF') {
    Modal.confirm({
      title: '警告',
      icon: createVNode(ExclamationCircleOutlined),
      content: `删除类目【${category.categoryName}】将会一并删除该类目下所有已配置的条件，是否继续？`,
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk() {
        onDeleteCategoryConfirm(category.id);
      },
      onCancel() {},
    });
  } else {
    if (category.children.length > 0) {
      message.info(
        `分类【${category.categoryName}】下有其他子分类或类目，无法删除。`,
      );
    } else {
      Modal.confirm({
        title: '警告',
        icon: createVNode(ExclamationCircleOutlined),
        content: `确认要删除分类【${category.categoryName}】吗？`,
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk() {
          onDeleteCategoryConfirm(category.id);
        },
        onCancel() {},
      });
    }
  }
};

const onDeleteCategoryConfirm = id => {
  const isSelect = id == currentSelectedKeys.value[0];
  deleteCategory(id).then(res => {
    useRes(res, () => {
      message.success('删除成功');
      if (isSelect) {
        currentSelectedKeys.value = [];
      }
      getCategoryTreeCaller();
    });
  });
};

const onResetCategoryConfirm = id => {
  resetCategory(id).then(res => {
    if (res.code === 'ok') {
      message.success('类目已重置');
      // 重置完直接获取详情
      fetchCategoryDetail();
    }
  });
};

const onOptionsClick = record => {
  const { conditionName, options } = record;
  optionModelTitle.value = conditionName;
  optionDataSource.value = options;
  optionModalOpen.value = true;
};

const onClassifyModalOk = category => {
  getCategoryTreeCaller();
  // // 如果更新的是选中的category，则还需要把基本信息刷新一遍
  // if (
  //   !!category &&
  //   currentSelectedKeys.value.length > 0 &&
  //   currentSelectedKeys.value[0] === category.id
  // ) {
  //   currentSelectedCategory.value = Object.assign(
  //     {},
  //     currentSelectedCategory.value,
  //     category
  //   );
  // }
};

// const onCategoryModalOk = () => {
//   getCategoryTreeCaller();
// };

const route = useRoute();

const getCategoryTreeCaller = async () => {
  treeLoading.value = true;
  await getCategoryTree()
    .then(res => {
      if (res.code === 'ok') {
        const data = res.data;
        breadFirstTree(
          data,
          node => {
            if (node.type !== 'LEAF') {
              node.selectable = false;
              // if (!treeLoaded.value) {
              //   currentExpandedKeys.value.push(node.id);
              // }
            }
            if (!node.parentId) {
              node.isRoot = true;
            }
            if (Array.isArray(node.children)) {
              node.children = node.children.map(ele => {
                ele.serialCount = node.children.length;
                return ele;
              });
            }
            return true;
          },
          'children',
        );
        treeData.value = data;
        treeLoaded.value = true;
      }
    })
    .finally(() => {
      treeLoading.value = false;
    });
};

const findNodeById = (id, tree) => {
  for (let item of tree) {
    if (item.id == id) return item;
    if (item.children) {
      const find = findNodeById(id, item.children);
      if (find) return find;
    }
  }
};

const { dragInit } = useDrag(
  filteredTreeData,
  async (nodeId, targetNodeId, position) => {
    treeLoading.value = true;
    const res = await put(Prefix.api + '/category/drag', {
      nodeId,
      targetNodeId,
      position,
    });
    if (res.code == 'ok') {
      getCategoryTreeCaller();
    } else {
      debugger;
      treeLoading.value = false;
      // message.error(res.message);
    }
  },
);
onMounted(async () => {
  await getCategoryTreeCaller();
  const categoryId = useCategoryStore().selectedCategory.id;
  if (categoryId) {
    const node = findNodeById(categoryId, treeData.value);
    const reg = /\[(.*?)\]/g;
    if (node.parentIds) {
      let match;
      const _expandKeys = [node.id];
      while ((match = reg.exec(node.parentIds))) {
        _expandKeys.unshift(+match[1]);
      }
      currentExpandedKeys.value = _expandKeys;
    }
    currentSelectedKeys.value = [~~categoryId];
    fetchCategoryDetail();
  }
  currentUser.value.isCategorySystemAdmin && dragInit();
});

const publishLoading = ref(false);
const publish = async code => {
  if (code == currentSelectedCategory.value.categoryCode) {
    publishLoading.value = true;
  }
  const res = await categoryPublish(code);
  if (code == currentSelectedCategory.value.categoryCode) {
    publishLoading.value = false;
  }
  useRes(res, () => {
    message.success('发布成功');
    getCategoryTreeCaller();
  });
};
const unPublish = async code => {
  if (code == currentSelectedCategory.value.categoryCode) {
    publishLoading.value = true;
  }
  const res = await categoryCancel(code);
  if (code == currentSelectedCategory.value.categoryCode) {
    publishLoading.value = false;
  }
  useRes(res, () => {
    message.success('取消发布成功');
    getCategoryTreeCaller();
  });
};

const publishFilters = [
  {
    title: '全部',
    key: 'all',
  },
  {
    title: '已发布',
    key: 'published',
  },
  {
    title: '未发布',
    key: 'unpublished',
  },
];
const filterPublish = ref('all');
const filterPublishActive = computed(() => filterPublish.value != 'all');
const changeFilterPublish = type => {
  filterPublish.value = type;
};

// 自建类目
const createCustom = () => {
  if (currentSelectedKeys.value.length === 0) {
    message.info('请选择一个类目');
    return;
  }
  const [id] = currentSelectedKeys.value;
  if (!canAction.value) {
    message.error('您不是该类目的创建人，无法操作');
    return;
  }
  router.push({
    path: '/custom-create',
  });
};

// 全部展开
const expandAll = () => {
  const list = [];
  const dfs = arr => {
    arr.forEach(node => {
      list.push(node.id);
      if (node.children?.length) {
        dfs(node.children);
      }
    });
  };
  dfs(treeData.value);
  currentExpandedKeys.value = list;
};

// 全部收起
const collapseAll = () => {
  currentExpandedKeys.value = [];
};

const treeRef = ref();
const goNode = () => {
  if (!currentSelectedCategory.value.id) return;
  treeRef.value?.scrollTo({
    key: currentSelectedCategory.value.id,
    align: 'top',
  });
};

const treeWrapperRef = ref();
const { height } = useElementSize(treeWrapperRef);
</script>

<script>
import {
  Button,
  Tree,
  Empty,
  Spin,
  Table,
  Input,
  DirectoryTree,
  Dropdown,
  Menu,
  MenuItem,
  message,
  Modal,
} from 'ant-design-vue';
import {
  MoreOutlined,
  ExclamationCircleOutlined,
  FolderOutlined,
  FolderOpenOutlined,
  ProfileOutlined,
  SearchOutlined,
} from '@ant-design/icons-vue';
import ClassifyModal from '@/components/cateogory/ClassifyModal.vue';
import DraggableSider from '@/components/commons/DraggableSider.vue';
import { categoryPublish, categoryCancel } from '@/api/split';

export default {
  components: {
    AInput: Input,
    AButton: Button,
    ATree: Tree,
    ASpin: Spin,
    AEmpty: Empty,
    ATable: Table,
    ADirectoryTree: DirectoryTree,
    ADropdown: Dropdown,
    AMenu: Menu,
    AMenuItem: MenuItem,
    MoreOutlined,
    ExclamationCircleOutlined,
    Modal,
    AModal: Modal,
    ClassifyModal,
    FolderOutlined,
    FolderOpenOutlined,
    ProfileOutlined,
    SearchOutlined,
  },
};
</script>

<style lang="scss" scoped>
.category-page {
  display: flex;
  flex: 1;

  .tree-wrapper {
    width: 100%;
    height: 100vh;
    overflow-y: hidden;
    display: flex;
    flex-direction: column;

    .tool-wrapper {
      padding: 8px 8px;
      border-bottom: 1px solid #d9d9d9;
    }

    :deep(.ant-tree-treenode) {
      .ant-tree-node-content-wrapper {
        padding-right: 12px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow-x: hidden;
      }

      .node {
        .icon-menu {
          position: absolute;
          right: 4px;
          top: 4px;
          z-index: 999;
          visibility: hidden;
        }

        &.selected {
          .icon-menu {
            visibility: visible;
          }
        }
      }

      &:hover {
        .node {
          .icon-menu {
            visibility: visible;
          }
        }
      }
    }
  }

  .info-wrapper {
    flex: 1;
    padding: 0 8px;
    overflow-y: auto;

    .basic-info-wrapper {
      display: flex;
      padding: 0 8px;

      img {
        width: 100px;
        height: 100px;
        margin-right: 16px;
      }
    }

    .table-wrapper {
      padding: 0 8px;
    }
  }

  .no-category-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    img {
      width: 400px;
    }

    div {
      font-size: 32px;
      margin-top: 16px;
      color: #197ce0;
    }
  }
}

.category-list {
  display: flex;
  flex-wrap: wrap;
  padding: 5px;

  .category-list-item {
    display: flex;
    width: 25%;
    padding: 10px;
    cursor: pointer;
    border-radius: 5px;

    &:hover {
      background: #b9d0e9;
    }

    img {
      width: 80px;
      height: 80px;
    }

    .content {
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding: 5px;
      overflow: hidden;

      span {
        width: 100%;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
}
</style>
